import 'dart:async';
import 'dart:convert';
import 'dart:ui';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:wanxiang_app/bean/banner_entity.dart';
import 'package:wanxiang_app/bean/deal_entity.dart';
import 'package:wanxiang_app/bean/game_list_entity.dart';
import 'package:wanxiang_app/pages/home/black.dart';
import 'package:wanxiang_app/pages/home/buyResult.dart';
import 'package:wanxiang_app/pages/home/detail.dart';
import 'package:wanxiang_app/pages/home/hot.dart';
import 'package:wanxiang_app/pages/home/liveList.dart';
import 'package:wanxiang_app/pages/home/qa.dart';
import 'package:wanxiang_app/pages/home/search.dart';
import 'package:wanxiang_app/pages/home/searchResult.dart';
import 'package:wanxiang_app/pages/home/service.dart';
import 'package:wanxiang_app/pages/home/tousu.dart';
import 'package:wanxiang_app/pages/my/priceMy.dart';
import 'package:wanxiang_app/utils/constant.dart';
import 'package:marquee_widget/marquee_widget.dart';
import 'package:get/get.dart';
import 'package:flutter_swiper_view/flutter_swiper_view.dart';

import '../../bean/anchor_entity.dart';
import '../../bean/goods_list_entity.dart';
import '../../utils/network_manager.dart';
import '../../utils/network_url.dart';
import '../../utils/toast_util.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../../widgets/simple_dialog.dart';
import 'package:scrollable_positioned_list/scrollable_positioned_list.dart';


class HomeController2 extends GetxController{
  int aa = 0;
  void increment(){
    aa ++ ;
    update();
  }

  @override
  void onInit() {
    super.onInit();

    _initAllData();
  }

  void _initAllData(){
    _getBannerData();
    _getGameListData();
    _getDealListData();
    _getAnchorListData();

  }

   List<BannerData> bannerData = [];
   List<GameListData> gameListData = [];
   List<DealData> dealList = [];
   List<AnchorData> anchorList = [];
  List<GoodsListData> goodsList = [];

  void _getBannerData(){
    Map map= {
      "banner_type":'banner_app',
    };
    DioManager.getInstance().post(ServiceUrl.banner, map, (data) async {
      BannerEntity bannerEntity = BannerEntity.fromJson(jsonDecode(data));
       bannerData = bannerEntity.data;
       update();
    }, (error) {
      ToastUtil.show(error);
    });
  }

  void _getGameListData(){
    Map map= {
      "top":'10',
    };
    DioManager.getInstance().post(ServiceUrl.gameList, map, (data) async {
      GameListEntity bannerEntity = GameListEntity.fromJson(jsonDecode(data));
      gameListData = bannerEntity.data;
      _getGoodslListData(gameListData[clickGameIndex].code);

      update();
    }, (error) {
      ToastUtil.show(error);
    });
  }


  void _getDealListData(){
    DioManager.getInstance().post(ServiceUrl.dealList, null, (data) async {
      DealEntity bannerEntity = DealEntity.fromJson(jsonDecode(data));
      dealList = bannerEntity.data;
      _startTimer();
    }, (error) {
      ToastUtil.show(error);
    });
  }

  void _getAnchorListData(){
    DioManager.getInstance().post(ServiceUrl.anchorList, null, (data) async {
      AnchorEntity bannerEntity = AnchorEntity.fromJson(jsonDecode(data));
      anchorList = bannerEntity.data;
      liveAnim();
      update();
    }, (error) {
      ToastUtil.show(error);
    });
  }

  void _getGoodslListData(name){
    DioManager.getInstance().post(ServiceUrl.goodsList, {
      'channel_name':name,
      'top':'3',
    }, (data) async {
      GoodsListEntity bannerEntity = GoodsListEntity.fromJson(jsonDecode(data));
      goodsList = bannerEntity.data;
      if(_hotTimer==null){
        hotAnim();
      }

      update();
    }, (error) {
      ToastUtil.show(error);
    });
  }

  int countValue = -1;
  late Timer _timer;
  void _startTimer() {
    const Duration duration = Duration(seconds: 2);
    _timer = Timer.periodic(duration, (timer) {
      if (countValue >= dealList.length-1) {
        countValue=0;
      }else{
        countValue = countValue +1;
      }
      update();

    });
  }

  void cancelTimer() {
    if (_timer != null) {
      _timer.cancel();
    }
  }
  int clickGameIndex = 0;
  changeGame(){
    _getGoodslListData(gameListData[clickGameIndex].code);
    update();
  }

  late BuildContext mContext ;
  showLive(url){
    showDialog(context: mContext, builder: (BuildContext context1) {
      return MySimpleDialog(callBack: (String content) {
        if(content == 'cancel'){
          Navigator.pop(context1);
        }else if(content == 'sure'){
          launchUrl(Uri.parse((url)));
          Navigator.pop(context1);
        }
      },
        msg: "查看主播详情将跳转至第三方网站",
        sureText: "确定",
      );
    });
  }

  final ItemScrollController itemScrollController = ItemScrollController();
  final ScrollOffsetController scrollOffsetController = ScrollOffsetController();
  final ItemPositionsListener itemPositionsListener = ItemPositionsListener.create();
  final ScrollOffsetListener scrollOffsetListener = ScrollOffsetListener.create();

  ScrollController hotScrollController = ScrollController();

  Timer? _hotTimer;
  hotAnim(){
    _hotTimer = Timer.periodic(const Duration(milliseconds: 2000), (timer) {
      clickGameIndex++;
      if(clickGameIndex==gameListData.length){
        clickGameIndex=0;
        itemScrollController.jumpTo(index: clickGameIndex);
      }
      // observerController?.jumpTo(index: clickGameIndex);
      if(clickGameIndex!=0){
        scrollOffsetController.animateScroll(offset: 80, duration: Duration(milliseconds: 2000));
      }

      // changeGame();
    });
  }

  Timer? _liveTimer;

  int liveIndex = 0;
  final ItemScrollController liveItemScrollController = ItemScrollController();
  final ScrollOffsetController liveScrollOffsetController = ScrollOffsetController();
  final ItemPositionsListener liveItemPositionsListener = ItemPositionsListener.create();
  final ScrollOffsetListener liveScrollOffsetListener = ScrollOffsetListener.create();

  liveAnim(){
    _liveTimer = Timer.periodic( Duration(milliseconds: (1500*anchorList.length)), (timer) {
      // liveIndex++;
      // if(liveIndex==anchorList.length){
      //   liveIndex=0;
        liveItemScrollController.jumpTo(index: 0);
      // }
        Future.delayed(Duration(seconds: 1),(){
          liveScrollOffsetController.animateScroll(offset: (142.0*anchorList.length), duration: Duration(milliseconds: 1500*anchorList.length-1000));
        });
      // observerController?.jumpTo(index: clickGameIndex);
      // if(liveIndex==0){

      // }

    });
  }


}

class HomePage2 extends GetView<HomeController2> {

  late HomeController2 controller ;
  late BuildContext context ;

  @override
  Widget build(BuildContext context1) {
    Get.lazyPut<HomeController2>(() => HomeController2());
    controller = Get.find();
    context = context1;
    controller.mContext= context1;
    return GetBuilder<HomeController2>(
      builder: (_){
        return  Scaffold(
          backgroundColor: Colors.white,
          body: SingleChildScrollView(
            child: _content(),
          ),
        );
      },
    )
     ;
  }
  
  Widget _content(){
    return Container(
      child: Column(
        children: [
          SizedBox(
            height: MediaQueryData.fromWindow(window).padding.top + 21.h,
          ),
          _top(),
          _swiper(),
          _tip(),
          _notice(),
          _hot('热门游戏','更多>>'),
          SizedBox(height: 10.h,),
          _hotList(),
          _line(),
          _hot('合作主播','更多>>'),
          _liveList(),
          _hot('最新上架','更多>>'),
          _gameNamesList(),
            Column(
              children: _gameListItems(),
            ),
          SizedBox(height: 30.h,)
        ],
      ),
    );
  }

  Widget _top(){
    return InkWell(
      onTap: (){
        Get.to(()=>SearchPage(),preventDuplicates:false);
      },
      child:   Container(
          margin: EdgeInsets.only(left: 16.w,right: 25.w),
          height: 32.h,
          alignment: Alignment.topCenter,
          child:
          Row(
            children: [
              Image.asset('assets/images/logo.png',width: 50.w,height: 19.h,),
              SizedBox(width: 17.w,),
              Expanded(
                  flex: 1,
                  child: Container(
                    height: 32.h,
                    decoration: BoxDecoration(
                        color: Color(0xFFF5F5F5),
                        borderRadius: BorderRadius.circular(17.r)
                    ),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        SizedBox(width: 18.w,),
                        Image.asset('assets/images/home_search.png',width: 14.w,height: 14.h,),
                        SizedBox(width: 8.w,),
                        Text('请输入游戏名称',style: TextStyle(
                            color: Color(0xFF8B8B8B),
                            fontSize: 13.sp
                        ),)
                      ],
                    ),
                  )),
              SizedBox(width: 21.w,),
              Image.asset('assets/images/home_service.png',width: 24.w,height: 22.h,),
            ],
          )
      )
    ) ;
  }

  Widget _swiper(){
    return Container(
      margin: EdgeInsets.only(left: 14.w,right: 16.w,top: 10.h),
      height: 120.h,
      width: 328.w,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(6.r),
      ),
      child: Swiper(
        itemBuilder: (context, index) {
          return CachedNetworkImage(imageUrl: controller.bannerData[index].url, imageBuilder: (context, imageProvider) => Container(
              height: 130.h,
              width: 328.w,
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: imageProvider,
                  fit: BoxFit.contain,
                ),
              )));
        },
        autoplay: false,
        itemCount: controller.bannerData.length,
        pagination: SwiperPagination(
            builder: SwiperCustomPagination(
                builder: (BuildContext context, SwiperPluginConfig config) {
                  return NLIndicator(config.activeIndex, controller.bannerData.length);
                })),
      ),
    );
  }

  Widget _tip(){
    return Container(
      margin: EdgeInsets.only(left: 16.w,right: 16.w,top: 5.h),
      child: Row(
        children: [
          InkWell(
            onTap: (){
              Get.to(()=>ServicePage(),preventDuplicates:false);
            },
            child:  Container(
              width: 100.w,height: 130.h,
              decoration: const BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage('assets/images/index_tip_1.png'),
                    fit: BoxFit.fill,
                  )
              ),
            )
          )
        ,
          SizedBox(width: 6.w,),
          Column(
            children: [
              Row(
                children: [
                  InkWell(
                      onTap: (){
                        Get.to(()=>BlackPage(),preventDuplicates:false);
                      },
                    child:   Container(
                      padding: EdgeInsets.only(left: 12.w),
                      width: 108.w,height: 60.h,
                      decoration: BoxDecoration(
                          image: DecorationImage(
                            image: AssetImage('assets/images/index_tip_2.png'),
                            fit: BoxFit.fill,
                          )
                      ),
                    )
                  )
                ,
                  SizedBox(width: 6.w,),
                  InkWell(
                    onTap: (){
                      // ToastUtil.show('暂未开通');
                      Get.to(()=>PriceMyPage(),preventDuplicates:false);
                    },
                    child:    Container(
                      padding: EdgeInsets.only(left: 12.w),
                      width: 108.w,height: 60.h,
                      decoration: BoxDecoration(
                          image: DecorationImage(
                            image: AssetImage('assets/images/index_tip_3.png'),
                            fit: BoxFit.fill,
                          )
                      ),
                    )
                  )
               ,
                ],
              ),


              SizedBox(height: 6.h,),
              Row(
                children: [
                  InkWell(
                    onTap: (){
                      Get.to(()=>TousuPage(),preventDuplicates:false);
                    },
                    child: Container(
                      padding: EdgeInsets.only(left: 12.w),
                      width: 108.w,height: 60.h,
                      decoration: BoxDecoration(
                          image: DecorationImage(
                            image: AssetImage('assets/images/index_tip_4.png'),
                            fit: BoxFit.fill,
                          )
                      ),
                    )
                  )
                  ,

                  SizedBox(width: 6.w,),

                  InkWell(
                    onTap: (){
                      Get.to(()=>QAPage(),arguments: '常见问题',preventDuplicates:false);
                    },
                    child:  Container(
                      padding: EdgeInsets.only(left: 12.w),
                      width: 108.w,height: 60.h,
                      decoration: BoxDecoration(
                          image: DecorationImage(
                            image: AssetImage('assets/images/index_tip_5.png'),
                            fit: BoxFit.fill,
                          )
                      ),
                    )
                  )
                 ,

                ],
              )
            ],
          )
        ],
      ),
    );
  }

  Widget _notice(){
    return Container(
      height: 41.h,
      width: 328.w,
      margin: EdgeInsets.only(left: 16.w,right: 16.w,top: 14.h),
      padding: EdgeInsets.fromLTRB(14.w, 14.h, 13.w, 13.h),
      decoration: BoxDecoration(
        color: Color(0xFFFFF9EB),
        borderRadius: BorderRadius.circular(6.r)
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Image.asset(Constant.IMG_BASE+'index_notice.png',width: 16.w,height: 14.h,),
          SizedBox(width: 11.w,),
          controller.countValue!=-1?
          Container(
            width: 266.w,
            child: Marquee(
              direction: Axis.vertical,
              animationDuration: const Duration(seconds: 1),
              directionMarguee: DirectionMarguee.oneDirection,
              child: Text(controller.dealList[controller.countValue].title,
                overflow: TextOverflow.ellipsis,
                softWrap: true,
                textAlign: TextAlign.left,
                style: TextStyle(fontSize: 12.sp),) ,
            )
          ):Container(),

        ],
      ),
    );
  }

  Widget _hot(leftText,rightText){
    return Container(
      margin: EdgeInsets.only(left: 17.w,right: 16.w,top: 10.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(leftText,style: TextStyle(color:const Color(0xFF333333),fontSize: 15.sp,fontWeight: FontWeight.bold ),),
          InkWell(
            onTap: (){
              if(leftText =='合作主播'){
                Get.to(()=>LivePage(),preventDuplicates:false);
              }else{
                Constant.clcikSellTab = false;
                Get.to(()=>HotPage('index'),arguments: {"type":1},preventDuplicates:false);
              }

            },
            child: Text(rightText,style: TextStyle(color:const Color(0xFF666666),fontSize: 13.sp ),),
          )

        ],
      ),
    );
  }


  Widget _hotList(){
    return
      Container(
        width: 328.w,
        height: 100.h,
        child: GridView.count(
          padding: EdgeInsets.all(0),
          physics: NeverScrollableScrollPhysics(),
          crossAxisCount: 5,
          mainAxisSpacing: 7.w,
          crossAxisSpacing: 18.h,
          childAspectRatio: 1 / 1,
          children: controller.gameListData.map((item) => _hotItem(item)).toList(),
        )
      );
  }

  Widget _hotItem(GameListData item){
    return InkWell(
      onTap: (){
        Get.to(()=>BuyResultPage(),
            preventDuplicates:false,
            arguments: {
          'channel_name':item.code,
          'channel_id':item.id,
          'keyword':'',
          'name':item.name
        });
      },
      child: Container(

        width: 60.w,
        height: 60.h,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(16.r),
        ),
        alignment: Alignment.center,
        child:

        CachedNetworkImage(imageUrl: item.backimg, imageBuilder: (context, imageProvider) => Container(
            width: 60.w,
            height: 60.w,
            decoration: BoxDecoration(
              image: DecorationImage(
                image: imageProvider,
                fit: BoxFit.cover,
              ),
            )))

        ,
      )
    ) ;
  }

  Widget _line(){
    return Container(
      margin: EdgeInsets.only(left: 16.w,right: 16.w,top: 10.h),
      height: 1.h,
      decoration: BoxDecoration(
        color: Color(0xFFF5F5F5),
      ),
    );
  }

  Widget _liveList(){
    // return
    //   Container(
    //     margin: EdgeInsets.fromLTRB(16.w, 8.h, 16.w, 0),
    //     child: SingleChildScrollView(
    //       scrollDirection:Axis.horizontal,
    //       child: Row(
    //         children: _liveListItems(),
    //       ),
    //     )
    //   )
    //   ;

    return Container(
        margin: EdgeInsets.fromLTRB(16.w, 8.h, 16.w, 0),
        height: 90.h,
        child: ScrollablePositionedList.builder(
          scrollDirection:Axis.horizontal,
          itemCount: controller.anchorList.length,
          itemBuilder: (context, index) => _liveItem(controller.anchorList[index]),
          itemScrollController: controller.liveItemScrollController,
          scrollOffsetController: controller.liveScrollOffsetController,
          itemPositionsListener: controller.liveItemPositionsListener,
          scrollOffsetListener: controller.liveScrollOffsetListener,
        )
    )
    ;


  }
  
  List<Widget> _liveListItems(){
    List<Widget> items = [];

    controller.anchorList.forEach((element) {
      items.add(_liveItem(element));
    });
   
    return items;
  }

  Widget _liveItem(AnchorData item){
    return InkWell(
      onTap: (){
        controller.showLive(item.openUrl);
      },
      child: Container(
        width: 142.w,
        height: 88.w,
        margin: EdgeInsets.only(right: 10.w),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(10.r),
          child: CachedNetworkImage(imageUrl: item.imgUrl, imageBuilder: (context, imageProvider) => Container(
              width: 142.w,
              height: 88.w,
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: imageProvider,
                  fit: BoxFit.cover,
                ),
              )))
        ,
        ),
      )
    ) ;
  }


  Widget _gameNamesList(){
    return Container(
        margin: EdgeInsets.fromLTRB(16.w, 10.h, 16.w, 0),
      height: 35.h,
      child: ScrollablePositionedList.builder(
        scrollDirection:Axis.horizontal,
        addRepaintBoundaries:false,
        itemCount: controller.gameListData.length,
          shrinkWrap:true,
        physics: ClampingScrollPhysics(),
        itemBuilder: (context, index) => _gameNameItems(controller.gameListData[index],index),
        itemScrollController: controller.itemScrollController,
        scrollOffsetController: controller.scrollOffsetController,
        itemPositionsListener: controller.itemPositionsListener,
        scrollOffsetListener: controller.scrollOffsetListener,
      )
    )
      ;

  }

  List<Widget> _gameNameListItems(){
    List<Widget> items = [];

    for(int i = 0;i<controller.gameListData.length;i++){
      items.add(_gameNameItems(controller.gameListData[i],i));
    }

    return items;
  }


  Widget _gameNameItems(element,index){

    return InkWell(
      onTap: (){
        controller.clickGameIndex = index;
        controller.changeGame();
      },
      child:  index == controller.clickGameIndex?_clickTag(element.name):
      _clickTagNo(element.name)
    );
  }

  Widget _clickTag(name){
    return  Container(
      alignment: Alignment.center,
      height: 30.h,
      padding: EdgeInsets.fromLTRB(12.w, 0, 12.w, 0),
      margin: EdgeInsets.only(right: 10.w),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10.r),
          color: Color(0xFFF43F50)
      ),
      child: Text(name,style: TextStyle(color: Colors.white,fontSize: 14.sp),),
    );
  }
  Widget _clickTagNo(name){
    return  Container(
      alignment: Alignment.center,
      height: 30.h,
      padding: EdgeInsets.fromLTRB(12.w, 0, 12.w, 0),
      margin: EdgeInsets.only(right: 10.w),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10.r),
          color: Color(0xFFEDEEEF),
      ),
      child: Text(name,style: TextStyle(color: Color(0xFF333333),fontSize: 14.sp),),

    );
  }

  List<Widget> _gameListItems(){
    List<Widget> items = [];
    for (var element in controller.goodsList) {
      items.add(_gameItems(element));
    }
    return items;
  }

  Widget _gameItems(GoodsListData item){
    return InkWell(
      onTap: (){
        Get.to(()=>DetailPage(),arguments: {
          "title":item.title,
          "record_id":item.channelId,
          "channel_name":item.channelName,
          "goods_id":item.id.toString(),
        },preventDuplicates:false);
      },
      child:  Container(
        margin: EdgeInsets.only(left: 16.w,right: 13.w,top: 10.h),
        child: Row(
          children: [
            Container(
                width: 120.w,
                height: 100.w,
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(12.r),
                  child:Stack(
                    children: [
                      Image.network(item.imgUrl,fit:BoxFit.cover,
                        width: 120.w,
                        height: 100.w,

                      ),
                      _officer(item),

                    ],
                  ),
                )
            ),
            SizedBox(width: 14.w,),
            Container(
                width: MediaQuery.of(context).size.width - 29.w - 14.w - 100.w - 20.w,
                child:  Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(item.title,
                      style: TextStyle(color: Color(0xFF333333),fontSize: 14.sp,fontWeight: FontWeight.bold),maxLines: 2,    textAlign: TextAlign.left,
                      overflow: TextOverflow.ellipsis,),
                    SizedBox(height: 10.h,),
                    Text('区服：${item.categoryText}',style: TextStyle(color: Color(0xFF666666),fontSize: 13.sp),),
                    SizedBox(height: 6.h,),
                    Row(
                      children: [
                        Text('售价：',style: TextStyle(color: Color(0xFF666666),fontSize: 12.sp),),
                        Text('¥',style: TextStyle(color: Color(0xFFFF0000),fontSize: 12.sp),),
                        Text(item.sellPrice,style: TextStyle(color: Color(0xFFFF0000),fontSize: 18.sp),),
                      ],
                    )
                  ],
                )
            )

          ],
        ),
      )
    );
  }

  Widget _officer(GoodsListData item) {
    return item.isSelf==0?  Container(
      child: Image.asset(Constant.IMG_BASE+'baopei.png',width: 52.w,height: 17.h,fit: BoxFit.fitWidth,),
    ):Container();
  }
}


class NLIndicator extends StatelessWidget {
  var _currentIndex;
  var _count;
  NLIndicator(this._currentIndex, this._count);
  @override
  Widget build(BuildContext context) {
    return Container(
      width: 150.w,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: List.generate(_count, (index){
          return _currentIndex == index ? Container(
            width: 24.w,
            height: 5.h,
            margin: EdgeInsets.only(right: 8.w),
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(4)
            ),
          ) : Container(
            width: 8.w,
            height: 8.h,
            margin: EdgeInsets.only(right: 8.w),
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(20)
            ),
          );
        }),
      ),
    );
  }
}

